package com.hznc.wcs.flowable.candidate;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.diboot.iam.entity.IamPosition;
import com.diboot.iam.service.IamPositionService;
import com.diboot.iam.service.IamUserPositionService;
import com.hznc.wcs.enums.BpmTaskCandidateStrategyEnum;

import com.hznc.wcs.exception.BusinessException;
import jakarta.annotation.Resource;
import org.apache.commons.lang3.StringUtils;
import org.flowable.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Component;

import java.util.Arrays;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 岗位 {@link BpmTaskCandidateStrategy} 实现类
 *
 * @author kyle
 */
@Component
public class BpmTaskCandidatePostStrategy implements BpmTaskCandidateStrategy {

    @Resource
    private IamPositionService iamPositionService;

    @Resource
    private IamUserPositionService iamUserPositionService;

    @Override
    public BpmTaskCandidateStrategyEnum getStrategy() {
        return BpmTaskCandidateStrategyEnum.POST;
    }

    @Override
    public void validateParam(String param) {
        String[] postIdAndNum = StringUtils.split(param, ",");
        List<String> list = Arrays.asList(postIdAndNum);
        List<String> postIdList = list.stream().map(item -> item.split("#")[0]).toList();
        for (String post:postIdList){
            LambdaQueryWrapper<IamPosition> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(IamPosition::getId,post);
            boolean exists = iamPositionService.exists(queryWrapper);
            if (!exists){
                throw new BusinessException("岗位不存在");
            }
        }
    }

    @Override
    public Set<String> calculateUsers(DelegateExecution execution, String param) {
        String[] postIdAndRoleNum = StringUtils.split(param, ",");
        List<String> list = Arrays.asList(postIdAndRoleNum);
        List<String> postIdList = list.stream().map(item -> item.split("#")[0]).toList();
        List<String> userIdsByPosition = iamUserPositionService.getUserIdsByPosition(null,postIdList);
        return new HashSet<>(userIdsByPosition);
    }

}